<template>
  <div class="page">
    <div class="page-header flex-row flex-center">
      <div class="header-wrapper flex-row">
        <div class="logo">
          <img src="./img/logo.png" />
        </div>
        <div class="title">仿真应用社区</div>
        <div class="operation"></div>
      </div>
    </div>

    <div class="page-body flex-column flex-center">
      <div class="body-wrapper">
        <!---- 轮播图 ----->
        <div class="banner flex-column">
          <div class="banner-title">仿真应用社区</div>
          <div class="banner-info">
            依托国家级超算互联网平台，构建超算应用的生态<br />
            涵盖各类课程、行业专家、专业资料、厂商软件、计算资源、应用开发
          </div>
          <div class="banner-btn flex-column flex-center">
            <a-button type="normal" shape="round" size="large" style="color: #fff; font-weight: 500" @click="navigateTo('/selected-content/list')">
              <template #icon>
                开始使用社区平台
                <ArrowRightOutlined />
              </template>
            </a-button>
          </div>
        </div>

        <!---- 课程精选 ----->
        <div class="selected flex-column">
          <div class="section-title flex-row">
            <div class="text">精选课程</div>
            <div class="more flex-row flex-center-end">
              <text-button label="查看全部" size="14" @click="navigateTo('/selected-content/courses')">
                <template #right>
                  <CaretRightOutlined />
                </template>
              </text-button>
            </div>
          </div>
          <div class="section-info">
            丰富多元且系统全面的课程知识库，无论您是初涉某个领域的新手，还是渴望深入钻研的进阶学习者，都能找到适合自己的学习资源。
          </div>
          <div class="selected-tabs">
            <a-tabs tab-position="left"
              @change="changeCourseTab"
              :tabBarStyle="{width: '220px', height: '550px', backgroundColor: '#FFE3E1', borderRadius: '20px 0 0 20px', padding: '20px 0'}">
              <!----- 入门课程 ----->
              <a-tab-pane v-if="isNotEmpty(storeHome.rumenCourseSource)" key="1">
                <template #tab>
                  <div class="tab-line">
                    <div class="tab-line-icon">
                      <img v-if="currentCourseTab=='1'" src="@/assets/icons/course-rumen-h.png" />
                      <img v-else src="@/assets/icons/course-rumen.png" />
                    </div>
                    <div class="tab-line-title" :class="currentCourseTab=='1' ? 'active' : ''">入门课程</div>
                  </div>
                </template>

                <a-flex wrap="wrap" gap="20" class="course-list">
                  <course-card v-for="item in storeHome.rumenCourseSource" :key="item.courseId"
                    :courseId="item.srcCourseId"
                    :courseTitle="item.name"
                    :courseImg="item.pic">
                  </course-card>
                </a-flex>
              </a-tab-pane>

              <!----- 进阶课程 ----->
              <a-tab-pane v-if="isNotEmpty(storeHome.jinjieCourseSource)" key="2">
                <template #tab>
                  <div class="tab-line">
                    <div class="tab-line-icon">
                      <img v-if="currentCourseTab=='2'" src="@/assets/icons/course-jinjie-h.png" />
                      <img v-else src="@/assets/icons/course-jinjie.png" />
                    </div>
                    <div class="tab-line-title" :class="currentCourseTab=='2' ? 'active' : ''">进阶课程</div>
                  </div>
                </template>

                <a-flex wrap="wrap" gap="20" class="course-list">
                  <course-card v-for="item in storeHome.jinjieCourseSource" :key="item.courseId"
                    :courseId="item.srcCourseId"
                    :courseTitle="item.name"
                    :courseImg="item.pic">
                  </course-card>
                </a-flex>
              </a-tab-pane>

              <!----- 高级课程 ----->
              <a-tab-pane v-if="isNotEmpty(storeHome.gaojiCourseSource)" key="3">
                <template #tab>
                  <div class="tab-line">
                    <div class="tab-line-icon">
                      <img v-if="currentCourseTab=='3'" src="@/assets/icons/course-gaoji-h.png" />
                      <img v-else src="@/assets/icons/course-gaoji.png" />
                    </div>
                    <div class="tab-line-title" :class="currentCourseTab=='3' ? 'active' : ''">高级课程</div>
                  </div>
                </template>

                <a-flex wrap="wrap" gap="20" class="course-list">
                  <course-card v-for="item in storeHome.gaojiCourseSource" :key="item.courseId"
                    :courseId="item.srcCourseId"
                    :courseTitle="item.name"
                    :courseImg="item.pic">
                  </course-card>
                </a-flex>
              </a-tab-pane>

              <!----- 实战课程 ----->
              <a-tab-pane v-if="isNotEmpty(storeHome.shizhanCourseSource)" key="4">
                <template #tab>
                  <div class="tab-line">
                    <div class="tab-line-icon">
                      <img v-if="currentCourseTab=='4'" src="@/assets/icons/course-shizhan-h.png" />
                      <img v-else src="@/assets/icons/course-shizhan.png" />
                    </div>
                    <div class="tab-line-title" :class="currentCourseTab=='4' ? 'active' : ''">实战课程</div>
                  </div>
                </template>

                <a-flex wrap="wrap" gap="20" class="course-list">
                  <course-card v-for="item in storeHome.shizhanCourseSource" :key="item.courseId"
                    :courseId="item.srcCourseId"
                    :courseTitle="item.name"
                    :courseImg="item.pic">
                  </course-card>
                </a-flex>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>

        <!---- 行家名师 ----->
        <div class="expert">
          <div class="section-title flex-row">
            <div class="text">行家名师</div>
            <div class="more"></div>
          </div>
          <div class="section-info">行业的精英荟萃之地，每一位名师都拥有深厚的学术造诣和丰富的实践经验。</div>
          <!---- 轮播图 ---->
          <a-carousel :autoplay="true" height="300" class="expert-container" :class="expertArray.length<=1 ? 'hide-dots' : ''">
            <div v-for="(experts, index) in expertArray" :key="index">
              <a-flex wrap="wrap" gap="20" class="expert-list" :class="expertArray.length<=1 ? 'hide-dots' : ''">
                <expert-card v-for="item in experts" :key="item.expertsId"
                  :name="item.name"
                  :alias="item.alias"
                  :pic="item.pic"
                  :remark="item.remark"
                  :tags="item.tags">
                </expert-card>
              </a-flex>
            </div>
          </a-carousel>
        </div>
        
        <!---- 资料下载 ----->
        <div class="material">
          <div class="section-title flex-row">
            <div class="text">资料下载</div>
            <div class="more flex-row flex-center-end">
              <text-button label="查看全部" size="14" @click="navigateTo('/selected-content/materials')">
                <template #right>
                  <CaretRightOutlined />
                </template>
              </text-button>
            </div>
          </div>
          <div class="section-info">从基础理论的扎实讲解，到实际操作的分步指南，仿真知识社区应有尽有。</div>
          <a-flex wrap="wrap" gap="20" class="material-list">
            <material-card v-for="item in storeHome.materialSource" :key="item.documentsId"
              :title="item.name"
              price="1299"
              @onDownload="doDownload(item.documentsId, item.url)">
            </material-card>
          </a-flex>
        </div>

        <!---- 软件下载 ----->
        <div v-if="isNotEmpty(storeHome.softwareSource)" class="software">
          <div class="section-title flex-row">
            <div class="text">热门软件</div>
            <div class="more flex-row flex-center-end">
              <text-button label="查看全部" size="14" @click="navigateTo('/selected-content/softwares')">
                <template #right>
                  <CaretRightOutlined />
                </template>
              </text-button>
            </div>
          </div>
          <div class="section-info">仿真应用社区有丰富的工业软件资源，涵盖多种领域。</div>
          <a-flex wrap="wrap" gap="20" class="software-list">
            <software-card v-for="item in storeHome.softwareSource" :key="item.id" :softwareInfo="item"></software-card>
          </a-flex>
        </div>
      </div>
    </div>

    <!---- 页尾图片 ----->
    <div class="page-footer">
      <div class="footer-bg"></div>
      <div class="footer-wrapper">
        <img src="./img/footer.png">
      </div>
    </div>

    <!---- 授权注册对话框 ----->
    <a-modal v-model:open="openLogin" title="" :footer="null" @ok="hideLogin">
      <div class="login-dialog">
        <div class="img-title">
          <img src="./img/login-logo.png" />
        </div>
        <div class="txt-app">同意注册社区应用服务</div>
        <div class="txt-online">在线使用社区学习资源、超算资源、各类软件及应用</div>
        <div class="btn-register">
          <a-button type="primary" shape="round"
            @click="doLogin"
            style="width: 100%; height: 100%;">
            授权注册
          </a-button>
        </div>
        <div class="btn-back">
          <a-button danger shape="round"
            @click="hideLogin"
            style="width: 100%; height: 100%;">
            返回
          </a-button>
        </div>
        <div class="txt-service">在线计算服务由仿真秀优质合作对象提供</div>
        <div class="chk-agreement">
          <a-tooltip :open="showTip" title="请先勾选同意开通">
            <a-checkbox
              :checked="chkAgree"
              @change="onCheckAgree"
            >
              点击同意开通即表示您同意《用户协议》和《隐私政策》
            </a-checkbox>
          </a-tooltip>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ArrowRightOutlined, CaretRightOutlined, AppleOutlined } from '@ant-design/icons-vue';
import { ref, onBeforeMount } from 'vue';
import { Modal } from 'ant-design-vue';
import { useNavigation } from "@utils/navigation";
import MaterialCard from '@components/MaterialCard.vue';
import CourseCard from '@components/CourseCard.vue'; 
import ExpertCard from '@components/ExpertCard.vue';
import SoftwareCard from '@components/SoftwareCard.vue';
import TextButton from '@components/TextButton.vue';
import useHomeStore from "@/stores/home";
import useAppStore from "@/stores/app";
import { isNotEmpty, splitArray, getLocalUserInfo } from "@/utils";
import { base58Decode, unit8ArrayToString } from '@/utils/base58';
import { downloadFile } from '@/utils/download';
import appConfig from '@/config';
import { miscApi } from "@/services";

const { navigateTo, redirectTo } = useNavigation();

const openLogin = ref<boolean>(false);
const showLogin = () => {
  openLogin.value = true;
  showTip.value = false;
};

const hideLogin = (e: MouseEvent) => {
  openLogin.value = false;
  showTip.value = false;
};

const storeApp = useAppStore();
const showTip = ref<boolean>(false);
const doLogin = async (e: MouseEvent) => {
  if (!chkAgree.value) {
    showTip.value = true;
    return;
  }

  if (!chkAgree.value) {
    return;
  }

  openLogin.value = false;
  storeApp.setUserInfo(await storeHome.getUserInfo());
  
  navigateTo('/selected-content/list');
};

const chkAgree = ref<boolean>(false);
const onCheckAgree = (e: Event) => {
  chkAgree.value = !chkAgree.value;
  showTip.value = !chkAgree.value;
};

const storeHome = useHomeStore();
const expertArray = ref([]);
const currentCourseTab = ref('1');
onBeforeMount(async () => {
  const url = new URL(window.location.href);
  const localToken = url.searchParams.get('localToken');
  console.log("SCNet localToken: ", localToken);
  if (localToken) {
    // 清除 URL 中的查询参数
    const cleanUrl = new URL(window.location.href);
    cleanUrl.search = ''; // 清空查询参数
    window.history.replaceState({}, '', cleanUrl.href);

    const decodeUnit8Array = base58Decode(localToken);
    console.log("SCNet decodeUnit8Array: ", decodeUnit8Array);
    const accountInfo = JSON.parse(unit8ArrayToString(decodeUnit8Array));
    console.log("SCNet accountInfo: ", accountInfo);

    if (accountInfo && accountInfo.errorMsg) {
      Modal.info({
        title: accountInfo.errorMsg,
        content: '',
        okText: '确定',
        async onOk() {
          localStorage.removeItem("userInfo");
          const url = await storeHome.getRedirectUrl();
          if (url!=null && url != "") {
            redirectTo(url);
          } else {
            redirectTo(appConfig.scnetLogin);
          }
        },
      });
      return false;
    }

    // 设置当前账号的token
    appConfig.apiToken = accountInfo.token;
  }
  
  await storeHome.initData();

  // 设置当前课程tab
  if (isNotEmpty(storeHome.rumenCourseSource)) {
    currentCourseTab.value = '1';
  } else if (isNotEmpty(storeHome.jinjieCourseSource)) {
    currentCourseTab.value = '2';
  } else if (isNotEmpty(storeHome.gaojiCourseSource)) {
    currentCourseTab.value = '3';
  } else if (isNotEmpty(storeHome.shizhanCourseSource)) {
    currentCourseTab.value = '4';
  }

  // 将行业专家每4个分成一组
  expertArray.value = splitArray(storeHome.expertListResult, 4);

  // 设置当前账号信息
  if (appConfig.apiToken) {
    storeApp.setUserToken(appConfig.apiToken);
    storeApp.setUserInfo(await storeHome.getUserInfo());
  } else {
    // storeApp.setUserToken('');
    // storeApp.setUserInfo(null);
  }

  miscApi.traceViewPage("/home")
});

const changeCourseTab = (key: string) => {
  currentCourseTab.value = key;
}

const doDownload = async (id: number, url:string) => {
  if (!url) {
    return;
  }

  const userInfo = getLocalUserInfo();
  if (!(userInfo && userInfo.username)) {
    const url = await storeHome.getRedirectUrl();
    if (url!=null && url != "") {
      window.location.href = url;
    } else {
      window.location.href = appConfig.scnetLogin;
    }
    return;
  }

  try {
    const fileName = url.split('/').pop();
    await downloadFile({
      url: url,
      fileName: fileName // 可选自定义文件名‌:ml-citation{ref="6" data="citationList"}
    })

    if (id) {
      // 保存到我的资料
      await storeHome.addAsMyMaterial(id);
    }
  } catch (error) {
    console.error(`下载文件 ${url} 出现异常`, error);
  }
}
</script>

<style lang="less" scoped>
  .page {
    width: 100%;

    .page-header {
      width: 100%;
      height: 80px;
      background: linear-gradient( 166deg, @red 0%, #AD0015 100%);
      box-shadow: 0px 10px 12px -5px rgba(153,153,153,0.5);

      .header-wrapper {
        width: 1200px;
        height: 40px;

        .logo {
          width: 40px;
          height: 100%;

          img {
            width: 100%;
            height: 100%;
          }
        }

        .title {
          width: 200px;
          line-height: 40px;
          font-size: 22px;
          font-weight: 500;
          padding-left: 12px;
          color: @white;
        }

        .operation {
          flex: 1;
        }
      }
    }

    .page-body {
      width: 100%;

      .body-wrapper {
        width: 1200px;

        .banner {
          width: 100%;
          height: 260px;
          margin-top: 10px;
          padding-left: 20px;
          background-image: url('./img/banner_bg.png');

          .banner-title {
            height: 56px;
            line-height: 56px;
            margin-top: 40px;
            font-weight: bold;
            font-size: 46px;
            color: @font-black;
          }

          .banner-info {
            height: 45px;
            line-height: 22px;
            margin-top: 10px;
            font-weight: 400;
            font-size: 16px;
            color: @font-grey;
          }

          .banner-btn {
            width: 180px;
            height: 40px;
            margin-top: 26px;
            background: linear-gradient( 166deg, @red 0%, #AD0015 100%);
            border-radius: 20px;
          }
        }

        .selected {
          width: 100%;
          margin-top: 40px;

          .selected-tabs {
            margin-top: 20px;
            min-height: 550px;
            background-color: @white;
            box-shadow: 0px 2px 10px 0px @box-shadow-color;
            border-radius: 20px;

            .course-list {
              padding: 20px 0;
              background-color: @white;
              border-radius: 20px;
            }

            :deep(.ant-tabs-nav-list) {
              .ant-tabs-tab {
                height: 60px;
                padding: 20px;

                &.ant-tabs-tab-active {
                  background-color: @white;
                }

                .ant-tabs-tab-btn {
                  .tab-line {
                    display: flex;
                    align-items: center;

                    .tab-line-icon {
                      width: 24px;
                      height: 24px;
                    }
                    .tab-line-title {
                      margin-left: 10px;
                      height: 20px;
                      line-height: 20px;
                      font-size: 20px;
                      font-weight: 500;
                      color: @font-black;

                      &.active {
                        color: @red;
                      }
                    }
                  }
                }
              }

              .ant-tabs-ink-bar {
                width: 4px;
                height: 30px;
                left: 0px;
              }
            }
          }
        }

        .expert {
          width: 100%;
          margin-top: 40px;

          .expert-info {
            width: 285px;
            height: 386px;
            background: @white;
            box-shadow: 0px 2px 10px 0px @box-shadow-color;
            border-radius: 20px;
          }

          .expert-container {
            width: 1200px;
            height: 446px;
            margin-top: 20px;

            &.hide-dots {
              height: 406px;
            }

            .expert-list {
              margin-bottom: 30px;
              height: 426px;

              &.hide-dots {
                height: 386px;
              }
            }
          }
        }

        .material {
          margin-top: 50px;
          width: 100%;

          .material-list {
            margin-top: 20px;

            .material-card {
              width: 590px;
            }
          }
        }

        .software {
          width: 100%;
          margin-top: 40px;

          .software-list {
            margin-top: 20px;
          }
        }

        .section-title {
          height: 24px;
          .text {
            width: 70%;
            height: 24px;
            line-height: 24px;
            font-size: 24px;
            font-weight: 500;
            color: @font-black;
          }
          .more {
            width: 30%;
            text-align: right;
          }
        }

        .section-info {
          margin-top: 10px;
          height: 16px;
          line-height: 16px;
          font-size: 16px;
          font-weight: 400;
          color: @font-grey-light;
        }
      }

      :deep(.ant-carousel) {
        .slick-dots-bottom {
          bottom: 0px;
        }
        
        .slick-dots li {
          width: 10px;
          height: 10px;
          margin-inline: 5px;

          button {
            width: 10px;
            height: 10px;
            border-radius: 5px;
            background: @font-grey-disable;
            opacity: 1;
          }

          &.slick-active{
            width: 40px;
            button {
              width: 40px;
              background: @red;
            }
          }
        }
      }
    }

    .page-footer {
      margin-top: 20px;
      height: 280px;
      position: relative;

      .footer-bg {
        width: 100%;
        height: 200px;
        position: absolute;
        bottom: 0px;
        background: linear-gradient( 180deg, #FCF2F1 0%, #F0ECEC 100%);
      }

      .footer-wrapper {
        width: 1200px;
        height: 280px;
        position: absolute;
        left: calc((100% - 1200px)/2);

        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .login-dialog{
    width: 460px;
    height: 370px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .img-title {
      height: 26px;
      margin-top: 25px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .txt-app {
      height: 24px;
      line-height: 24px;
      font-size: 24px;
      font-weight: 500;
      color: @font-black;
      margin-top: 33px;
    }

    .txt-online {
      line-height: 16px;
      height: 16px;
      font-size: 16px;
      font-weight: 400;
      color: @font-black;
      margin-top: 20px;
    }

    .btn-register {
      width: 380px;
      height: 40px;
      margin-top: 40px;
    }

    .btn-back {
      width: 380px;
      height: 40px;
      margin-top: 10px;
    }

    .txt-service {
      margin-top: 10px;
    }

    .chk-agreement {
      margin-top: 5px;
    }
  }
</style>
